package com.baidu.iit.pvm.runtime;

import com.baidu.iit.pvm.PvmEventConstacts;
import com.baidu.iit.pvm.process.ActivityImpl;
import com.baidu.iit.pvm.process.ScopeImpl;

/**
 * 用于单元节点的删除操作
 *
 * @ThreadSafe
 *
 * Created by 卫立 on 2014/4/7.
 */
public class AtomicOperationDeleteCascadeFireActivityEnd extends AbstractEventAtomicOperation {



    @Override
    protected ScopeImpl getScope(InterpretableExecution execution) {
        ActivityImpl activity = (ActivityImpl) execution.getActivity();
        if (activity != null) {
            return activity;
        } else {
            InterpretableExecution parent = (InterpretableExecution) execution.getParent();
            if (parent != null) {
                return getScope((InterpretableExecution) execution.getParent());
            }
            return execution.getProcessDefinition();
        }
    }

    @Override
    protected String getEventName() {
        return PvmEventConstacts.EVENTNAME_END;
    }

    @Override
    protected void eventNotificationsCompleted(InterpretableExecution execution) {
        ActivityImpl activity = (ActivityImpl) execution.getActivity();
        if ((execution.isScope())
                && (activity != null)
                && (!activity.isScope())
                ) {
            execution.setActivity(activity.getParentActivity());
            execution.performOperation(AtomicOperation.DELETE_CASCADE_FIRE_ACTIVITY_END);

        } else {
            if (execution.isScope()) {
                execution.destroy();
            }
            execution.remove();
            if (!execution.isDeleteRoot()) {
                InterpretableExecution parent = (InterpretableExecution) execution.getParent();
                if (parent != null) {
                    parent.performOperation(AtomicOperation.DELETE_CASCADE);
                }
            }
        }
    }
}
